//
//  HRTokenExpires.m
//  Hear
//
//  Created by mac on 2017/3/27.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRTokenExpires.h"

@implementation HRTokenExpires
- (void)isTokenExpires:(void(^)(BOOL result))loginResult
{
    NSDate * lastGetTokenTimeDate =  [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGetTokenTime"];
    NSString * tokenExpireTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"expires_in"];//token多少秒之后过期时间

    if (!lastGetTokenTimeDate){
        [HRTokenExpires getAccessToken:^(BOOL result) {
            loginResult(result);
        }];
    }
    
    NSDate * nowdate = [NSDate date];
    
    NSTimeInterval secondsInterval = [nowdate timeIntervalSinceDate:lastGetTokenTimeDate];
    
    //时间差大于令牌过期时间返回yes重新获取令牌
    if ((tokenExpireTime.floatValue - secondsInterval) > 10) {
        return loginResult(YES);
    }else{
        [HRTokenExpires getAccessToken:^(BOOL result) {
            loginResult(result);
        }];
        
    }
    
}


+ (void)getAccessToken:(void(^)(BOOL result))loginResult
{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"grant_type"] = @"client_credentials";
    YTKApi *api = [YTKApi apiPostWithUrl:@"token" para:paramDict];
    api.foceNoTocken = YES;
    [api setRequestSerializerType:YTKRequestSerializerTypeHTTP];
    [api startWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = request.responseJSONObject;
        [[NSUserDefaults standardUserDefaults] setObject:dict[@"access_token"] forKey:@"access_token"];
        [[NSUserDefaults standardUserDefaults] setObject:dict[@"expires_in"] forKey:@"expires_in"];
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastGetTokenTime"];
        loginResult(YES);

    }];
}




@end
